// 书签管理系统 - 主应用程序
class BookmarkApp {
    constructor() {
        this.storage = new BookmarkStorage();
        this.currentCategory = '';
        this.currentSort = 'sort';
        this.currentSearch = '';
        this.editingBookmarkId = null;
        this.init();
    }

    // 初始化应用
    init() {
        this.bindEvents();
        this.loadCategories();
        this.loadBookmarks();
        this.updateCounts();
    }

    // 绑定事件
    bindEvents() {
        // 添加书签按钮
        document.getElementById('addBookmarkBtn').addEventListener('click', () => {
            this.showBookmarkModal();
        });

        // 添加分类按钮
        document.getElementById('addCategoryBtn').addEventListener('click', () => {
            this.showCategoryModal();
        });

        // 导出按钮
        document.getElementById('exportBtn').addEventListener('click', () => {
            this.exportData();
        });

        // 导入按钮
        document.getElementById('importBtn').addEventListener('click', () => {
            document.getElementById('importFile').click();
        });

        // 文件导入
        document.getElementById('importFile').addEventListener('change', (e) => {
            this.importData(e.target.files[0]);
        });

        // 搜索框
        document.getElementById('searchInput').addEventListener('input', (e) => {
            this.currentSearch = e.target.value;
            this.loadBookmarks();
        });

        // 分类筛选
        document.getElementById('categoryFilter').addEventListener('change', (e) => {
            this.currentCategory = e.target.value;
            this.loadBookmarks();
        });

        // 排序选择
        document.getElementById('sortBy').addEventListener('change', (e) => {
            this.currentSort = e.target.value;
            this.loadBookmarks();
        });

        // 书签表单
        document.getElementById('bookmarkForm').addEventListener('submit', (e) => {
            e.preventDefault();
            this.saveBookmark();
        });

        // 分类表单
        document.getElementById('categoryForm').addEventListener('submit', (e) => {
            e.preventDefault();
            this.saveCategory();
        });

        // 模态框关闭
        this.bindModalEvents();
    }

    // 绑定模态框事件
    bindModalEvents() {
        // 书签模态框
        const bookmarkModal = document.getElementById('bookmarkModal');
        const closeBookmarkModal = () => {
            bookmarkModal.style.display = 'none';
            this.resetBookmarkForm();
        };

        document.getElementById('closeModal').addEventListener('click', closeBookmarkModal);
        document.getElementById('cancelBtn').addEventListener('click', closeBookmarkModal);
        
        bookmarkModal.addEventListener('click', (e) => {
            if (e.target === bookmarkModal) closeBookmarkModal();
        });

        // 分类模态框
        const categoryModal = document.getElementById('categoryModal');
        const closeCategoryModal = () => {
            categoryModal.style.display = 'none';
            this.resetCategoryForm();
        };

        document.getElementById('closeCategoryModal').addEventListener('click', closeCategoryModal);
        document.getElementById('cancelCategoryBtn').addEventListener('click', closeCategoryModal);
        
        categoryModal.addEventListener('click', (e) => {
            if (e.target === categoryModal) closeCategoryModal();
        });

        // 确认删除模态框
        const confirmModal = document.getElementById('confirmModal');
        const closeConfirmModal = () => {
            confirmModal.style.display = 'none';
        };

        document.getElementById('closeConfirmModal').addEventListener('click', closeConfirmModal);
        document.getElementById('cancelDeleteBtn').addEventListener('click', closeConfirmModal);
        
        confirmModal.addEventListener('click', (e) => {
            if (e.target === confirmModal) closeConfirmModal();
        });
    }

    // 加载分类
    loadCategories() {
        const categories = this.storage.getCategories();
        const categoriesNav = document.getElementById('categoriesNav');
        const categoryFilter = document.getElementById('categoryFilter');
        const bookmarkCategory = document.getElementById('bookmarkCategory');

        // 更新分类导航
        categoriesNav.innerHTML = `
            <div class="category-tab ${this.currentCategory === '' ? 'active' : ''}" data-category="">
                <span>全部</span>
                <span class="count" id="allCount">0</span>
            </div>
        `;

        // 更新筛选下拉框
        categoryFilter.innerHTML = '<option value="">所有分类</option>';
        bookmarkCategory.innerHTML = '<option value="">未分类</option>';

        categories.forEach(category => {
            // 分类导航标签
            const tabHtml = `
                <div class="category-tab ${this.currentCategory === category.id ? 'active' : ''}" 
                     data-category="${category.id}" style="border-color: ${category.color}">
                    <span>${category.name}</span>
                    <span class="count" id="count_${category.id}">0</span>
                    ${category.id !== 'default' ? `<button class="category-delete" onclick="app.deleteCategory('${category.id}')" title="删除分类">×</button>` : ''}
                </div>
            `;
            categoriesNav.insertAdjacentHTML('beforeend', tabHtml);

            // 筛选下拉框选项
            const filterOption = document.createElement('option');
            filterOption.value = category.id;
            filterOption.textContent = category.name;
            categoryFilter.appendChild(filterOption);

            // 书签分类下拉框选项
            const bookmarkOption = document.createElement('option');
            bookmarkOption.value = category.id;
            bookmarkOption.textContent = category.name;
            bookmarkCategory.appendChild(bookmarkOption);
        });

        // 绑定分类标签点击事件
        categoriesNav.addEventListener('click', (e) => {
            const tab = e.target.closest('.category-tab');
            if (tab && !e.target.classList.contains('category-delete')) {
                this.selectCategory(tab.dataset.category);
            }
        });

        // 设置当前选中的分类
        categoryFilter.value = this.currentCategory;
    }

    // 选择分类
    selectCategory(categoryId) {
        this.currentCategory = categoryId;
        document.getElementById('categoryFilter').value = categoryId;
        
        // 更新分类标签样式
        document.querySelectorAll('.category-tab').forEach(tab => {
            tab.classList.toggle('active', tab.dataset.category === categoryId);
        });

        this.loadBookmarks();
    }

    // 加载书签
    loadBookmarks() {
        let bookmarks = this.storage.getBookmarks();

        // 应用搜索过滤
        if (this.currentSearch.trim()) {
            bookmarks = this.storage.searchBookmarks(this.currentSearch);
        }

        // 应用分类过滤
        if (this.currentCategory) {
            bookmarks = bookmarks.filter(b => b.category === this.currentCategory);
        }

        // 排序
        bookmarks = this.storage.sortBookmarks(bookmarks, this.currentSort);

        // 渲染书签列表
        this.renderBookmarks(bookmarks);
        this.updateCounts();
    }

    // 渲染书签列表
    renderBookmarks(bookmarks) {
        const bookmarksList = document.getElementById('bookmarksList');
        const emptyState = document.getElementById('emptyState');

        if (bookmarks.length === 0) {
            bookmarksList.style.display = 'none';
            emptyState.style.display = 'block';
            return;
        }

        emptyState.style.display = 'none';
        bookmarksList.style.display = 'grid';

        const categories = this.storage.getCategories();
        const categoryMap = categories.reduce((map, cat) => {
            map[cat.id] = cat;
            return map;
        }, {});

        bookmarksList.innerHTML = bookmarks.map(bookmark => {
            const category = categoryMap[bookmark.category];
            const categoryDisplay = category ? 
                `<div class="bookmark-category" style="background-color: ${category.color}">${category.name}</div>` : 
                (bookmark.category ? `<div class="bookmark-category">未知分类</div>` : '');

            return `
                <div class="bookmark-item" data-id="${bookmark.id}">
                    <div class="bookmark-header">
                        <div>
                            ${categoryDisplay}
                            <div class="bookmark-title">${this.escapeHtml(bookmark.name)}</div>
                            <a href="${bookmark.url}" target="_blank" class="bookmark-url" 
                               onclick="event.stopPropagation()">${this.escapeHtml(bookmark.url)}</a>
                        </div>
                        <div class="bookmark-actions">
                            <button class="action-btn edit-btn" onclick="app.editBookmark(${bookmark.id})" title="编辑">
                                ✏️
                            </button>
                            <button class="action-btn delete-btn" onclick="app.deleteBookmark(${bookmark.id})" title="删除">
                                🗑️
                            </button>
                        </div>
                    </div>
                    ${bookmark.notes ? `<div class="bookmark-notes">${this.escapeHtml(bookmark.notes)}</div>` : ''}
                    <div class="bookmark-meta">
                        <span>创建时间: ${this.formatDate(bookmark.created)}</span>
                        <span class="bookmark-sort">排序: ${bookmark.sort}</span>
                    </div>
                </div>
            `;
        }).join('');

        // 绑定书签项点击事件（用于快速访问）
        bookmarksList.addEventListener('click', (e) => {
            const bookmarkItem = e.target.closest('.bookmark-item');
            if (bookmarkItem && !e.target.closest('.bookmark-actions') && !e.target.closest('.bookmark-url')) {
                const bookmark = this.storage.getBookmark(parseInt(bookmarkItem.dataset.id));
                if (bookmark) {
                    window.open(bookmark.url, '_blank');
                }
            }
        });
    }

    // 更新计数
    updateCounts() {
        const stats = this.storage.getCategoryStats();
        const allCount = Object.values(stats).reduce((sum, count) => sum + count, 0);
        
        document.getElementById('allCount').textContent = allCount;
        
        Object.entries(stats).forEach(([categoryId, count]) => {
            const countElement = document.getElementById(`count_${categoryId}`);
            if (countElement) {
                countElement.textContent = count;
            }
        });
    }

    // 显示书签模态框
    showBookmarkModal(bookmarkId = null) {
        this.editingBookmarkId = bookmarkId;
        const modal = document.getElementById('bookmarkModal');
        const modalTitle = document.getElementById('modalTitle');
        
        modalTitle.textContent = bookmarkId ? '编辑书签' : '添加书签';
        
        if (bookmarkId) {
            this.fillBookmarkForm(bookmarkId);
        } else {
            this.resetBookmarkForm();
        }
        
        modal.style.display = 'block';
    }

    // 填充书签表单
    fillBookmarkForm(bookmarkId) {
        const bookmark = this.storage.getBookmark(bookmarkId);
        if (!bookmark) return;

        document.getElementById('bookmarkName').value = bookmark.name;
        document.getElementById('bookmarkUrl').value = bookmark.url;
        document.getElementById('bookmarkCategory').value = bookmark.category || '';
        document.getElementById('bookmarkSort').value = bookmark.sort;
        document.getElementById('bookmarkNotes').value = bookmark.notes || '';
    }

    // 重置书签表单
    resetBookmarkForm() {
        document.getElementById('bookmarkForm').reset();
        document.getElementById('bookmarkSort').value = '0';
        this.editingBookmarkId = null;
    }

    // 保存书签
    saveBookmark() {
        const name = document.getElementById('bookmarkName').value.trim();
        const url = document.getElementById('bookmarkUrl').value.trim();
        const category = document.getElementById('bookmarkCategory').value;
        const sort = parseInt(document.getElementById('bookmarkSort').value) || 0;
        const notes = document.getElementById('bookmarkNotes').value.trim();

        const bookmarkData = { name, url, category, sort, notes };
        const validation = this.storage.validateBookmark(bookmarkData);

        if (!validation.valid) {
            alert('请检查输入：\n' + validation.errors.join('\n'));
            return;
        }

        let success;
        if (this.editingBookmarkId) {
            success = this.storage.updateBookmark(this.editingBookmarkId, bookmarkData);
        } else {
            success = this.storage.addBookmark(bookmarkData);
        }

        if (success) {
            document.getElementById('bookmarkModal').style.display = 'none';
            this.resetBookmarkForm();
            this.loadBookmarks();
            this.showToast(this.editingBookmarkId ? '书签已更新' : '书签已添加');
        } else {
            alert('保存失败，请重试');
        }
    }

    // 编辑书签
    editBookmark(bookmarkId) {
        this.showBookmarkModal(bookmarkId);
    }

    // 删除书签
    deleteBookmark(bookmarkId) {
        const bookmark = this.storage.getBookmark(bookmarkId);
        if (!bookmark) return;

        this.showConfirmModal(
            `确定要删除书签"${bookmark.name}"吗？`,
            () => {
                if (this.storage.deleteBookmark(bookmarkId)) {
                    this.loadBookmarks();
                    this.showToast('书签已删除');
                } else {
                    alert('删除失败，请重试');
                }
            }
        );
    }

    // 显示分类模态框
    showCategoryModal() {
        document.getElementById('categoryModal').style.display = 'block';
        this.resetCategoryForm();
    }

    // 重置分类表单
    resetCategoryForm() {
        document.getElementById('categoryForm').reset();
    }

    // 保存分类
    saveCategory() {
        const name = document.getElementById('categoryName').value.trim();
        const color = document.getElementById('categoryColor').value;

        if (!name) {
            alert('请输入分类名称');
            return;
        }

        const result = this.storage.addCategory({ name, color });
        if (result) {
            document.getElementById('categoryModal').style.display = 'none';
            this.resetCategoryForm();
            this.loadCategories();
            this.showToast('分类已添加');
        } else {
            alert('分类名称已存在或保存失败');
        }
    }

    // 删除分类
    deleteCategory(categoryId) {
        const categories = this.storage.getCategories();
        const category = categories.find(c => c.id === categoryId);
        if (!category) return;

        this.showConfirmModal(
            `确定要删除分类"${category.name}"吗？\n该分类下的书签将移动到"未分类"`,
            () => {
                if (this.storage.deleteCategory(categoryId)) {
                    this.loadCategories();
                    this.loadBookmarks();
                    this.showToast('分类已删除');
                } else {
                    alert('无法删除该分类');
                }
            }
        );
    }

    // 显示确认模态框
    showConfirmModal(message, onConfirm) {
        document.getElementById('confirmMessage').textContent = message;
        document.getElementById('confirmModal').style.display = 'block';
        
        const confirmBtn = document.getElementById('confirmDeleteBtn');
        const newConfirmBtn = confirmBtn.cloneNode(true);
        confirmBtn.parentNode.replaceChild(newConfirmBtn, confirmBtn);
        
        newConfirmBtn.addEventListener('click', () => {
            document.getElementById('confirmModal').style.display = 'none';
            onConfirm();
        });
    }

    // 导出数据
    exportData() {
        if (this.storage.backupToFile()) {
            this.showToast('数据已导出');
        } else {
            alert('导出失败');
        }
    }

    // 导入数据
    importData(file) {
        if (!file) return;

        const reader = new FileReader();
        reader.onload = (e) => {
            try {
                const result = this.storage.importData(e.target.result);
                if (result.success) {
                    this.loadCategories();
                    this.loadBookmarks();
                    this.showToast(`导入成功！书签: ${result.imported.bookmarks}, 分类: ${result.imported.categories}`);
                } else {
                    alert('导入失败：' + result.error);
                }
            } catch (error) {
                alert('文件格式错误：' + error.message);
            }
        };
        reader.readAsText(file);
    }

    // 显示提示消息
    showToast(message) {
        // 创建提示元素
        const toast = document.createElement('div');
        toast.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            background: linear-gradient(45deg, #667eea, #764ba2);
            color: white;
            padding: 15px 25px;
            border-radius: 12px;
            font-size: 14px;
            font-weight: 600;
            box-shadow: 0 8px 25px rgba(102, 126, 234, 0.4);
            z-index: 10000;
            transform: translateX(400px);
            transition: transform 0.3s ease;
        `;
        toast.textContent = message;
        document.body.appendChild(toast);

        // 动画显示
        setTimeout(() => {
            toast.style.transform = 'translateX(0)';
        }, 100);

        // 自动隐藏
        setTimeout(() => {
            toast.style.transform = 'translateX(400px)';
            setTimeout(() => {
                document.body.removeChild(toast);
            }, 300);
        }, 3000);
    }

    // HTML转义
    escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    // 格式化日期
    formatDate(dateString) {
        const date = new Date(dateString);
        return date.toLocaleDateString('zh-CN') + ' ' + date.toLocaleTimeString('zh-CN', { 
            hour: '2-digit', 
            minute: '2-digit' 
        });
    }
}

// 初始化应用
let app;
document.addEventListener('DOMContentLoaded', () => {
    app = new BookmarkApp();
});

// 键盘快捷键
document.addEventListener('keydown', (e) => {
    // Ctrl+K 或 Cmd+K 快速搜索
    if ((e.ctrlKey || e.metaKey) && e.key === 'k') {
        e.preventDefault();
        document.getElementById('searchInput').focus();
    }
    
    // Ctrl+N 或 Cmd+N 添加书签
    if ((e.ctrlKey || e.metaKey) && e.key === 'n') {
        e.preventDefault();
        app.showBookmarkModal();
    }
    
    // ESC 关闭模态框
    if (e.key === 'Escape') {
        const openModal = document.querySelector('.modal[style*="block"]');
        if (openModal) {
            openModal.style.display = 'none';
            if (openModal.id === 'bookmarkModal') {
                app.resetBookmarkForm();
            } else if (openModal.id === 'categoryModal') {
                app.resetCategoryForm();
            }
        }
    }
});